import { getMockRecentChats, type ChatRecord } from '@/api/chat'

// 主题映射
const topicMap: Record<string, string> = {
  'pipeline-construction': '管道施工',
  'pipeline-maintenance': '管道维修', 
  'welding-construction': '焊接施工注意',
  'safety-standards': '施工安全规范',
  'quality-control': '工程质量控制'
}

// 主题图标映射
const topicIconMap: Record<string, string> = {
  'pipeline-construction': `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M3 12h18m-9-9v18" stroke="currentColor" stroke-width="2" fill="none"/></svg>`,
  'pipeline-maintenance': `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z" stroke="currentColor" stroke-width="2" fill="none"/></svg>`,
  'welding-construction': `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" stroke="currentColor" stroke-width="2" fill="none"/></svg>`,
  'safety-standards': `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" stroke="currentColor" stroke-width="2" fill="none"/></svg>`,
  'quality-control': `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" stroke="currentColor" stroke-width="2" fill="none"/></svg>`
}

// 默认图标（当没有匹配的主题时使用）
const defaultIcon = `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>`

// 侧边栏项接口
interface SidebarItem {
  key: string
  label: string
  icon: string
  path?: string
  parent?: string
  children?: SidebarItem[]
}

/**
 * 根据聊天记录生成侧边栏菜单项
 * @param chatRecords 聊天记录数组
 * @returns 侧边栏菜单项数组
 */
export function generateRecentChatsMenu(chatRecords: ChatRecord[]): SidebarItem[] {
  return chatRecords.map((chat, index) => {
    const topic = chat.topic || ''
    const topicName = topicMap[topic] || chat.title
    const icon = topicIconMap[topic] || defaultIcon
    
    return {
      key: `recent-chat-${chat.id}`,
      label: topicName,
      parent: 'recent-chats-parent',
      path: `/chat?chatId=${chat.id}`,
      icon: icon
    }
  })
}

/**
 * 获取最新的聊天记录并生成菜单
 * @param limit 限制数量，默认3条
 * @returns 侧边栏菜单项数组
 */
export async function getRecentChatsMenu(limit: number = 3): Promise<SidebarItem[]> {
  try {
    // 在实际环境中，这里应该调用真实的API
    // const chatRecords = await getRecentChats(limit)
    
    // 目前使用模拟数据
    const chatRecords = getMockRecentChats(limit)
    return generateRecentChatsMenu(chatRecords)
  } catch (error) {
    console.error('获取近期对话失败:', error)
    return []
  }
}

/**
 * 更新侧边栏中的近期对话菜单
 * @param sidebarItems 当前的侧边栏项
 * @param recentChatsMenu 新的近期对话菜单
 * @returns 更新后的侧边栏项
 */
export function updateSidebarWithRecentChats(
  sidebarItems: SidebarItem[], 
  recentChatsMenu: SidebarItem[]
): SidebarItem[] {
  return sidebarItems.map(item => {
    if (item.key === 'recent-chats-parent') {
      // 找到"查看更多"菜单项
      const viewMoreItem = item.children?.find(child => child.key === 'recent-chats')
      
      return {
        ...item,
        children: [
          ...recentChatsMenu,
          ...(viewMoreItem ? [viewMoreItem] : [])
        ]
      }
    }
    return item
  })
}

/**
 * 格式化时间显示
 * @param date 日期对象
 * @returns 格式化的时间字符串
 */
export function formatChatTime(date: Date): string {
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}
